//
//  CommentsViewController.m
//  Housekeeping
//
//  Created by 辰领科技 on 16/5/24.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "CommentsViewController.h"
#import "CommentsTableViewCell.h"

static NSString *CellIdentifier = @"CommentsTableViewCell";
@interface CommentsViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;


@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *CommentsArray;
@property(nonatomic,strong)NSMutableArray * heightArray;
@end

@implementation CommentsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _CommentsArray= [NSMutableArray array];
    _heightArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
 
    [self.tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
    self.tableView.showsVerticalScrollIndicator = NO;
    
    
}


#pragma mark - <UITableViewDelegate&&UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = _CommentsArray.count;
    return count;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height= [_heightArray[indexPath.row] floatValue]*VerticalRatio();
    return height ;
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentsTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell= [[CommentsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    NSDictionary * dic = _CommentsArray[indexPath.row];
    NSString * image= [NSString stringWithFormat:@"%@",dic[@"mgooImg"]];
    if (image.length>0) {
        [cell.commentImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    
    cell.commentTitle.text = [NSString stringWithFormat:@"%@",dic[@"mgooName"]];
    cell.commentDetail.frame = flexibleFrame(CGRectMake(68, 35, 244, 39), NO);
    cell.commentDetail.numberOfLines = 0;
    cell.commentDetail.text = [NSString stringWithFormat:@"%@",dic[@"mgcoContent"]];
    [cell.commentDetail sizeToFit];
    
    NSString * date = [NSString stringWithFormat:@"%@",dic[@"mgcoDate"]];
    if (date.length>=19) {
        cell.commentDate.text = [date substringToIndex:19];
    }
    
    UIView * line =[[UILabel alloc]init];
    line.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
    CGFloat height= [_heightArray[indexPath.row] floatValue];
    line.frame = flexibleFrame(CGRectMake(10, height-1, 300, 1), NO);
    [cell addSubview:line];
   
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - 返回
- (IBAction)Back:(id)sender {
    [self backBtn];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self requestData];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.CommentsArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self requestData];
        });
    }
    
}


#pragma   mark - 网络请求
- (void)requestData {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][Key_User_userId] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInt:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInt:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMyMallGoodsComment withHttpType:@"POST" withTag:HK_HK_queryMyMallGoodsComment];
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    
    if (tag == HK_HK_queryMyMallGoodsComment){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }else  {

            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.CommentsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.CommentsArray addObject:entity];
                }
               
                for (int i = 0 ; i<_CommentsArray.count; i++) {
                    NSInteger height = 73;
                    int lines = 0;
                     NSString * comment = _CommentsArray[i][@"mgcoContent"];
                    CGSize cSize = [comment sizeWithFont:[UIFont systemFontOfSize:11*VerticalTexeRatio()]];
                    lines = cSize.width/(244*VerticalRatio())  ;
                    if (lines>2) {
                        lines-=1;
                    }
                    height  += lines * 14;
                    
                    [_heightArray addObject:@(height)];

                }
                
                
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
        }
    }
    
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [self dismissWaitDialog];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
